#include <iostream>
#include <string>
#include <pthread.h>
#include <unistd.h>
pthread_mutex_t mutex;
pthread_cond_t conda, condb;
int ret = 1;
void *APrintf(void *args)
{
    while (true)
    {
        pthread_mutex_lock(&mutex);
        while (!ret)
        {
            pthread_cond_wait(&conda, &mutex);
        }
        std::cout << "我是线程A,打印线程A" << std::endl;
        ret = 0;
        // 给线程a发信号
        pthread_mutex_unlock(&mutex);
        pthread_cond_signal(&condb);
    }
    return nullptr;
}
void *BPrintf(void *args)
{
    while (true)
    {
        sleep(1);
        pthread_mutex_lock(&mutex);
        while (ret)
        {
            pthread_cond_wait(&condb, &mutex);
        }
        std::cout << "我是线程B,打印线程B" << std::endl;
        ret = 1;
        pthread_mutex_unlock(&mutex);
        pthread_cond_signal(&conda);
    }
    return nullptr;
}
int main()
{
    pthread_mutex_init(&mutex, nullptr);
    pthread_cond_init(&conda, nullptr);
    pthread_cond_init(&condb, nullptr);
    pthread_t a, b;
    pthread_create(&a, nullptr, APrintf, 0);
    pthread_create(&b, nullptr, BPrintf, 0);
    pthread_join(a,nullptr);
    pthread_join(b,nullptr);
    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&conda);
    pthread_cond_destroy(&condb);
    return 0;
}